import re
import irc.client

from kivy.logger import Logger

class ClientEventHandlerViewModel(object):

    server_pattern = re.compile(r'((\w+\.){2}\w+)')

    def __init__(self, connection, target, appdata):
        self._connection = connection
        self._target = target
        self._appdata = appdata
        self._server = None
        # register this view model to handle data from the irc client
        appdata['client'].register_view_model(self)
        # initialize self._server
        if self.connected:
            self.server

    @property
    def connected(self):
        if self._connection is not None:
            return self._connection.connected
        else:
            return False
                
    @property
    def server(self):
        if self._server is None and self._connection is not None:
            self._server = self._connection.server
        return self._server
        
    @property
    def target(self):
        return self._target

    @property
    def connection(self):
        return self._connection

    def _is_a_server(self, target):
        match = ClientEventHandlerViewModel.server_pattern.match(target)
        return match is not None

    def _servers_match(self, server):
        parts1 = self.server.split('.')
        parts2 = server.split('.')
        if len(parts1) == 3 and len(parts2) == 3:
            if parts1[1] == parts2[1] and\
               parts1[2] == parts2[2]:
                return True
        return False

    def _am_target(self, evsource, evserver=None):
        if '!' in evsource and '@' in evsource:
            nmask = NickMask(evsource)
            source = nmask.nick
        else:
            source = evsource
        ok = self._target == source
        if ok and evserver is not None:
            ok = evserver == self.server
        return ok

    # client methods
    
    def handle_client_event(self, evtarget, evtype, evserver, evsource, evargs):
        """
        abstract method
        
        handle an event from the client

        will use self._am_target(target) for some evtype
        """
        pass

    def handle_on_connect(self, connection):
        self._connection = connection
        # initialize self._server
        self.server

    def handle_on_disconnect(self):
        self._connection = None
        self._appdata['connection_vm'].remove_connection_page(self.server, self.target)
        
    def handle_on_remove(self):
        # this view is being removed
        # unregister from the client
        self._appdata['client'].unregister_view_model(self)
